package com.sjsoft.chat.video;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.sjsoft.Utils.networkUtility;
import com.sjsoft.adapter.MessageAdapter;
import com.sjsoft.adapter.VideoAdapter;
import com.sjsoft.app.video.R;
import com.sjsoft.application.chatVideoApp;
import com.sjsoft.constant.Constant;
import com.sjsoft.interfaces.OnDownloadCompleteListener;
import com.sjsoft.interfaces.OnDownloadStartListener;
import com.sjsoft.interfaces.OnUploadingCompleteListener;
import com.sjsoft.interfaces.OnUploadingStartListener;
import com.sjsoft.model.CSubCategory;
import com.sjsoft.model.IDownloadedItem;
import com.sjsoft.model.SmsItem;
import com.sjsoft.model.messageItem;
import com.sjsoft.model.videoItem;
import com.sjsoft.payment.PayCard;
import com.sjsoft.payment.PaySms;
import com.sjsoft.services.download.DownloadService;
import com.sjsoft.services.download.ServiceQueueDownloadUtil;
import com.sjsoft.video.LoadAmoutInfor;
import com.sjsoft.video.LoadPrefixcode;
import com.sjsoft.video.LoadVideoInfo;
import com.sjsoft.webservice.GetVersionService;
import com.sjsoft.webservice.GetVersionThread;
import com.sjsoft.webservice.GetVideoService;
import com.sjsoft.webservice.GetVideoThread;
import com.sjsoft.webservice.ServiceQueueUploadingUtil;
import com.sjsoft.webservice.ServiceQueueUploadingVideo;
import com.sjsoft.webservice.UtilsJson;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;

import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;

@SuppressLint("NewApi")
public class mainTab extends ActivityGroup implements Constant{

	public static TabHost mTabHost;
	
	Animation animFlipInForeward;
    Animation animFlipOutForeward;
    
    protected chatVideoApp application;
	
	protected ProgressDialog loading;
	private ProgressBar loadingVideo;
	
    protected Context context;
    int currentView = 0;
	int currentPosition = 0; // mark the previous position
	private static int maxTabIndex = 3;
    
    private ViewFlipper viewFlipperBody; // the tabhost body ViewFlipper
    
    //play video
    private VideoView mVideoView;	
	private ImageView img_thum;
	LinearLayout detail_activity;
	LinearLayout pay_money;
	
	private boolean bPlaying = false;
	private boolean bPause = false;
	private int stopPosition = 0;
	private boolean bDetail = false;
	private boolean bPay = false;
	private videoItem currentVideo = null;
	
	private boolean bStopMessage = true;
	private int nPosMessage;
	Toast mToast;
	PendingIntent sender;
	private boolean bKillThreadMsg = false;
	
	//Variable for update
	private String path;
	private String urlPath;
	private String message;
    
	 //@SuppressLint({ "NewApi", "NewApi", "NewApi" })
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    	super.onCreate(savedInstanceState);	    
	    	setContentView(R.layout.main_layout);	
	    	//set up some parameter
	    	
	    	this.context = this;
	    	this.application = (chatVideoApp)getApplicationContext();
	    	
	    	getImei();
	    	getVersionName();
	    	
	    	animFlipInForeward = AnimationUtils.loadAnimation(this, R.anim.flipin);
	        animFlipOutForeward = AnimationUtils.loadAnimation(this, R.anim.flipout);
	        
	        currentPosition = 1;
	        initControl();
	    	
	        //Create thread load the data from server
	        
			/*
	        if (android.os.Build.VERSION.SDK_INT > 9) {
	        	StrictMode.ThreadPolicy policy = 
	        		new StrictMode.ThreadPolicy.Builder().permitAll().build();
	        	StrictMode.setThreadPolicy(policy);
	        }
	        */
	        startGetInforAcount();
	        startCheckVersion();
	        final ImageView imgPayment = (ImageView)findViewById(R.id.img_pay);
	        imgPayment.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub					
					startPayment();				
				}
			});
	        loadCategory();
	        
		}
	 
	 private void startGetInforAcount()
	 {
		 LoadAmoutInfor loadInfor = new LoadAmoutInfor(context);
		 loadInfor.execute();
	 }
	 protected void initControl()
	 {
		 loading = new ProgressDialog(context);
		 loading.setMessage("Đang tải dữ liệu...");
		 loading.setCancelable(true);
		 
		 
		 Context context = getBaseContext();
		 LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		 detail_activity = (LinearLayout) inflater.inflate(R.layout.detail_activity_layout, null);
		 
		 pay_money = (LinearLayout) inflater.inflate(R.layout.pay_money, null);
			
		 initClickSend();
		 initClickClear();
		 
		 setupMobiCard();
		 setupVinaCard();
		 setupViettelCard();
		 setupSms5();
		 setupSms10();
		 setupSms15();
		 setupTabHost();	
		
	 }
	 
	 private void setupTabHost()
	 {
		 mTabHost = (TabHost)findViewById(R.id.mainTab);
	     mTabHost.setup(this.getLocalActivityManager());
	     viewFlipperBody = (ViewFlipper) mTabHost.getTabContentView();
			mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

				public void onTabChanged(String tabId) {
					// TODO Auto-generated method stub	
					if(bDetail == true)				  
				    	stopVideo();
				    	
					currentView = mTabHost.getCurrentTab();
					chatVideoApp application = (chatVideoApp)getApplicationContext();
					application.addPosTab(new Integer(currentView));
				    chatVideoApp.appendLog("current tab " +currentView);
				    
				    int nRealTab = application.getRealTab(new Integer(currentView));
					//nPosTab = currentView;			
					nRealTab += 2;										
					viewFlipperBody.refreshDrawableState();					
					viewFlipperBody.setDisplayedChild(currentPosition);
					viewFlipperBody.setInAnimation(animFlipInForeward);
					viewFlipperBody.setOutAnimation(animFlipOutForeward);
					viewFlipperBody.setDisplayedChild(nRealTab);	
					chatVideoApp.appendLog("Change from  " +currentPosition +"to " + nRealTab);
					currentPosition = nRealTab;
					ImageView imgPayment = (ImageView)findViewById(R.id.img_pay);
					imgPayment.setImageResource(R.drawable.addmoney);
					
				}
			});
	 }
	 
	 private void loadCategory() {
			if (networkUtility.getInstance(context).isNetworkAvailable()) {
				
				LoadPrefixcode Prefixcode = new LoadPrefixcode(context,getImei(),getVersionName());
				Prefixcode.execute();
				
				final LoadCategories loadCategories = new LoadCategories("-1");
				loadCategories.execute();
				loading.setOnCancelListener(new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						if (!loadCategories.isCancelled()
								&& (application.videoByCategory == null || application.videoByCategory
										.size() == 0)) {
							android.os.Process.killProcess(android.os.Process
									.myPid());
							finish();
						}
					}
				});
			} else {
				showNetworkErr();
			}

		}
	 private String getVersionName() {
			try {
				String sVersion = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
				application.sVersion = sVersion;
				return sVersion;
			} catch (Exception e) {
				application.sVersion = "1.0";
				return "1.0";
			}
		}
	    
	    private String getImei() {
			TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
			if(telephonyManager != null)
			{
				String sImei = telephonyManager.getDeviceId();
				application.sImei = sImei;
				return sImei;
			}
			return null;
		}
	 
	 private void showNetworkErr() {
			final AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle(getString(R.string.text_no_conection));
			alert.setPositiveButton(getResources().getString(R.string.text_exit),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							
							finish();
						}
					});
			alert.setNegativeButton(getString(R.string.text_again),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							loadCategory();
							dialog.cancel();
						}
					});
			alert.show();
		}
	 
	 protected void showDialogExit() {
			final AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle(getString(R.string.text_exit_question));
			alert.setPositiveButton(getResources().getString(R.string.text_ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							android.os.Process.killProcess(android.os.Process
									.myPid());
							finish();
						}
					});
			alert.setNegativeButton(getString(R.string.text_no),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							dialog.cancel();
						}
					});
			alert.show();
		}
	 			
		
	 class LoadCategories extends AsyncTask<Void, Void, Void> {
			int resultRequest;
			String id;
			boolean isNetWork = true;

			public LoadCategories(String id) {
				this.id = id;
				isNetWork = networkUtility.getInstance(context)
						.isNetworkAvailable();
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				if (isNetWork) {
					loading.show();
				} else {
					showNetworkErr();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (isNetWork) {
					
					String sCategory = UtilsJson.getExtendId();
					if(sCategory != null)
					{
						ArrayList<CSubCategory> list =  UtilsJson.getListSubByExtendId(sCategory);			
						if(list.size() > 0)
						{
							String sJsonListCategories = UtilsJson.getCategoryVideo(list.get(0).getExtendId());
							if(sJsonListCategories != null)
							{
								application.videoByCategory = UtilsJson.getListSubByExtendId(sJsonListCategories);
																
							}
						}							
					}
										
				} else {
					showNetworkErr();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				if (application.videoByCategory != null && application.videoByCategory.size() > 0) {
					updateTab();
					loadListVideo();
				} else {
					showNetworkErr();
				}
				
			}
		}
	 
	 Handler handleUpdateAdapter = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case 0:
					View tab1 = viewFlipperBody.getChildAt(2);
					if(tab1 != null)
					{
						ListVideo listVideo = (ListVideo)tab1.getContext();
						if(listVideo != null)
						{
							ArrayList<videoItem> list = application.arrTopVideo;
							if(list != null && list.size() > 0)
							{
								VideoAdapter newAdapter = new VideoAdapter(listVideo);
								newAdapter.addItems(list);
								listVideo.updateListVideo(newAdapter);								
							
							}
							
						}
					}
					break;
				
				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
	
		private void updatevideoTopNew() {
			application.arrTopVideo = application.arrAdapterInit.get(0);
			handleUpdateAdapter.sendEmptyMessage(0);
		}
		private void saveToList(String json) {
			ArrayList<videoItem> list = UtilsJson.getListVideoFromJson(json);			
			application.arrAdapterInit.add(list);
		}
		
	 private void loadListVideo() {
		 ServiceQueueUploadingVideo
					.setonGetDateStartListener(new OnUploadingStartListener() {
						@Override
						public void OnGetDataStart(String url) {
							// TODO Auto-generated method stub
						}
					});
			ServiceQueueUploadingVideo
					.setonGetDataCompleteListener(new OnUploadingCompleteListener() {

						@Override
						public void OnGetDataComplete(Context context,
								String response) {
							// TODO Auto-generated method stub
							int nPosTab = GetVideoThread.curState;
							saveToList(response);
								//update data for first tab
							GetVideoThread.curState = nPosTab +1;
							if(nPosTab == application.videoByCategory.size()-1)
							{
								updatevideoTopNew();
								loading.cancel();
							}
						}

						@Override
						public void onGetVideoComplete(Context context,
								ArrayList<videoItem> listVideo) {
							// TODO Auto-generated method stub
							int nPosTab = GetVideoThread.curState;
							application.arrAdapterInit.add(listVideo);
							if(nPosTab == mTabHost.getChildCount()-1)
							{
								//update data for first tab	
								updatevideoTopNew();
								GetVideoThread.curState = 1;
								loading.cancel();
							}
							else						
								GetVideoThread.curState = nPosTab +1;
							
							
						}
					});
			startService();//get List video
		}
	 
	 private void startService() {
		 
			Intent intent = new Intent(this, GetVideoService.class);
			Bundle sendBundle = new Bundle();
			intent.putExtras(sendBundle);
			startService(intent);
			GetVideoThread.curState = 0; //Start tab
		}
	 
	 public void startPayment()
	 {
		 //Intent payIntent = new Intent().setClass(this, PayMoney.class);
		
		 //startActivity(payIntent);
		 if(bDetail == true )
		 {
	    	stopVideo();
			bDetail = false;
			bPay = false;
			bStopMessage = true;
				
		  }
		 viewFlipperBody.setDisplayedChild(1);
		 viewFlipperBody.setInAnimation(animFlipInForeward);
		 viewFlipperBody.setOutAnimation(animFlipOutForeward);
		 viewFlipperBody.setDisplayedChild(1);
		 bPay = true;
		 ImageView imgPayment = (ImageView)findViewById(R.id.img_pay);
		 imgPayment.setImageResource(R.drawable.addmoneyselected);
	 }
	 
	 
	 public void updateTab()
	 {
		 int nSize = this.application.videoByCategory.size();
		 
		 	Intent videoIntent;
	    	videoIntent = new Intent().setClass(this, ListVideo.class);
	    	for(int i = 0; i< nSize; i++)
	    	{	 	
	    		CSubCategory item = application.videoByCategory.get(i);	    		
	    		setupTab(new TextView(this), item.getName(), videoIntent);
	    	}
	    	
			
	    	if(nSize > 0)
	    	{
				viewFlipperBody.addView(detail_activity,0);
				viewFlipperBody.addView(pay_money,1);
				application.addPosTab(new Integer(0));
				//add more other view				
	    	}
			
			
			mVideoView = (VideoView)detail_activity.findViewById(R.id.mainVideo);
	    	loadingVideo = (ProgressBar)detail_activity.findViewById(R.id.loading_video); 
	    		
			
	 }
	 
	 public  void initClickSend()
	 {
		 ImageView img_send = (ImageView)detail_activity.findViewById(R.id.image_gui);
		 if(img_send != null)
		 {
			 img_send.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					sendMessage();
				}
			});
		 }
	 }
	 
	 public void initClickClear()
	 {
		 ImageView img_ntn_clear = (ImageView)detail_activity.findViewById(R.id.image_chat_off);
		 if(img_ntn_clear != null)
		 {
			 img_ntn_clear.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					clearMessage();
				}
			});
		 }
	 }
	 
	 public void clearMessage()
	 {
		 EditText content = (EditText)detail_activity.findViewById(R.id.edit_content_chat);
		 if(content != null)
			 content.setText("");
	 }
	 
	 public void sendMessage()
	 {
		 //create a one message 
		 
		 EditText content = (EditText)detail_activity.findViewById(R.id.edit_content_chat);
		 String message = content.getText().toString();
		 if(!message.equalsIgnoreCase(""))
		 {
			 messageItem item = new messageItem( message, null,1);
			 content.setText("");
			 addMessage(item);//member
			 
			 int nMaxMes = chatVideoApp.arrMessage.size();
			 if(nPosMessage < nMaxMes-1)
			 {
				 nPosMessage ++;
				 messageItem mesItem = chatVideoApp.arrMessage.get(nPosMessage);	
				 addMessage(mesItem);
			 }
		 }
		 
	 }
	 @Override
	  public void onBackPressed() {
	    if(bDetail == true || bPay == true)
	    {
	    	stopVideo();
	    	currentView = mTabHost.getCurrentTab();
	    	int nRealTab = application.getRealTab(currentView);
	    	currentView +=2;
	    	viewFlipperBody.setDisplayedChild(0);
			
			viewFlipperBody.setInAnimation(animFlipInForeward);
			viewFlipperBody.setOutAnimation(animFlipOutForeward);
			viewFlipperBody.setDisplayedChild(nRealTab+2);
			bDetail = false;
			bPay = false;
			bStopMessage = true;
			ImageView imgPayment = (ImageView)findViewById(R.id.img_pay);
			imgPayment.setImageResource(R.drawable.addmoney);
	    }
	    else
	    	super.onBackPressed();
	  }
	 
	 private void PlayVideo(String videoPath)
	 {
		 if(bDetail == false)
			 return;
		 loadingVideo.setVisibility(View.VISIBLE);
	  try
	       {           
	               Uri video = Uri.parse(videoPath );             
	              
	               mVideoView.setVideoURI(video);
	               mVideoView.setOnPreparedListener (new OnPreparedListener() {                    
	           	    @Override
	           	    public void onPrepared(MediaPlayer mp) {
	           	        mp.setLooping(true);
	           	    }
	           	});
	              	              
	                      
	               mVideoView.setOnPreparedListener(new OnPreparedListener()
	               {
	            	   
	                   public void onPrepared(MediaPlayer mp)
	                   {                  
	                	   loadingVideo.setVisibility(View.INVISIBLE);  
	                	   //add first item
	                	   if(application.arrMessage!= null && application.arrMessage.size() > 0)
	                	   {
	                		   messageItem item = application.arrMessage.get(0);
	                		   addMessage(item);
	                		   TextView title = (TextView)detail_activity.findViewById(R.id.text_title);
	                			 title.setText(item._nameMember);	
	                		   nPosMessage = 1;	                		   
	                	   	   startShowMessage();
	                	   }
	                	   ImageView img_thumbnail = (ImageView)detail_activity.findViewById(R.id.img_video);
	                	   img_thumbnail.setVisibility(View.GONE);	
	                       mVideoView.start();
	                       refreshDetail(false);
	                   }
	               });       
	               
	               mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
	                   public void onCompletion(MediaPlayer mp) {	                           
	                           mp.reset();                          
	                   }
	               });
	               
	               mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener(){

					@Override
					public boolean onError(MediaPlayer mp, int arg1, int arg2) {
						// TODO Auto-generated method stub
						loadingVideo.setVisibility(View.INVISIBLE);
						refreshDetail(true);
						return true;
					}
	            	   
	               });
	               mVideoView.requestFocus();

	            }
	       catch(Exception e)
	       {
	    	   loadingVideo.setVisibility(View.INVISIBLE);
	                System.out.println("Video Play Error :"+e.toString());
	                finish();
	       }   

	 }
	 	 
	 public void refreshDetail(boolean bOffline)
	 {
		 ImageView img_send = (ImageView)detail_activity.findViewById(R.id.image_gui);
		 EditText content = (EditText)detail_activity.findViewById(R.id.edit_content_chat);
		 ImageView img_clear = (ImageView)detail_activity.findViewById(R.id.image_chat_off);
		 if(bOffline == true)
		 {
			 TextView title = (TextView)detail_activity.findViewById(R.id.text_title);
			 title.setText("Offline");
			 img_send.setVisibility(View.INVISIBLE);
			 content.setVisibility(View.INVISIBLE);
			 img_clear.setVisibility(View.INVISIBLE);
			 
		 }
		 else
		 {
			 img_send.setVisibility(View.VISIBLE);
			 content.setVisibility(View.VISIBLE);
			 img_clear.setVisibility(View.VISIBLE);
		 }
		 
	 }
	 public void stopVideo()
	 {
		 bStopMessage = true;
		 if(bPlaying == true)	    	
			 mVideoView.pause();	
		 	mVideoView.suspend();
		 	mVideoView.clearFocus();
	    	
	    	bPlaying = false;
	    	bPause = false;
	 }
	 public void viewDetail()
	 {		 
		 clearListChat();			
		 viewFlipperBody.setDisplayedChild(0);
		 viewFlipperBody.setInAnimation(animFlipInForeward);
		 viewFlipperBody.setOutAnimation(animFlipOutForeward);
		 viewFlipperBody.setDisplayedChild(0);
		 
		 bDetail = true;		 
		 TextView title = (TextView)detail_activity.findViewById(R.id.text_title);
		 title.setText(currentVideo.getName());	
		 final ImageView img_thumbnail = (ImageView)detail_activity.findViewById(R.id.img_video);
		 img_thumbnail.setVisibility(View.VISIBLE);		
	     String URLstring= currentVideo.getLink();
	     application.arrMessage = currentVideo.getMessage();
	     PlayVideo(URLstring);
	     clearListChat();
	     
		 
	 }
	 
	 public void setCurVideo(videoItem current)
	 {
		 
		 currentVideo = current;
	 }
	 
	 Handler updateMessage = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					if(chatVideoApp.arrMessage.size()> nPosMessage )
					{
						addMessage(chatVideoApp.arrMessage.get(nPosMessage));//auto
						nPosMessage ++;
					}
					else
					{
						bStopMessage = true;
					}
					break;

				default:
					break;
				}
				super.handleMessage(msg);
			}
		};

		
	 public  void startShowMessage()
	 {		
		 bStopMessage = false;
		 //create a new thread to update list view
		 Thread messageThread = new Thread() {
				int waited = 0;
				@Override
				public void run() {
					try {
						
						while (!bStopMessage && chatVideoApp.arrMessage.size() > nPosMessage) {
							sleep(100);	
							waited += 100;
							if(waited == 20000)
							{
								waited = 0;
								updateMessage.sendEmptyMessage(0);
								
							}
							
						}
					} catch (InterruptedException e) {
						// do nothing
						
					} finally {
						
					}
				}
			};
			messageThread.start();
					
         
	 }
	 
	 public void addMessage(messageItem item)
	 {
		 ListView listMes = (ListView)detail_activity.findViewById(R.id.list_chat_content);
		 
		 MessageAdapter msgAdapter = (MessageAdapter)listMes.getAdapter();
		 if(msgAdapter == null)
		 {			
			 List<messageItem> list = new ArrayList<messageItem>();
			 list.add(item);
			 msgAdapter = new MessageAdapter(this, list);			
			 listMes.setAdapter(msgAdapter);
		 }
		 else
		 {			 
			 msgAdapter.addMoreItem(item);
			 msgAdapter.notifyDataSetChanged();
		 }
		 listMes.setSelection(listMes.getAdapter().getCount()-1);
			 
	 }
	 
	 public void clearListChat()
	 {
		 ListView listMes = (ListView)detail_activity.findViewById(R.id.list_chat_content);
		 if(listMes != null)
		 {
			 MessageAdapter msgAdapter = (MessageAdapter)listMes.getAdapter();
			 if(msgAdapter != null)
			 {			
				 msgAdapter.clear();
				 msgAdapter.notifyDataSetChanged();
			 }
		 } 
		
	 }
	 
	 private void setupTab(final View view, final String tag, final Intent myIntent) {

			View tabview = createTabView(mTabHost.getContext(), tag);
			TabSpec setContent =  mTabHost.newTabSpec(tag)
										  .setIndicator(tabview)										  
										  .setContent(myIntent);
			mTabHost.addTab(setContent);
			
			//mTabHost.getTabWidget().getChildAt(0).getLayoutParams().height =30;
		}

	 private static View createTabView(final Context context, final String text) {
			View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);//history: video_tab_layout
			TextView tv = (TextView) view.findViewById(R.id.tabsText);
			tv.setText(text);
			return view;
		}
	 
	 /*=====================Payment============================*/
	 
	 public void setupMobiCard()
	    {
	    	ImageView mobi_img = (ImageView)pay_money.findViewById(R.id.img_mobi);
	    	mobi_img.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					startActivityCard("VMS");
				}
			});
	    }
	    
	    public void setupVinaCard()
	    {
	    	ImageView vina_img = (ImageView)pay_money.findViewById(R.id.img_vina);
	    	vina_img.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					startActivityCard("VNP");
				}
			});
	    }
	    
	    public void setupViettelCard()
	    {
	    	ImageView vietel_img = (ImageView)pay_money.findViewById(R.id.img_viettel);
	    	vietel_img.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					startActivityCard("VTE");
				}
			});
	    }
	       
	    public void setupSms15()
	    {
	    	ImageView sms15_img = (ImageView)pay_money.findViewById(R.id.img_sms15);
	    	sms15_img.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub							
						startActivitySms(3);					
				}
			});
	    }
	    
	    public void setupSms5()
	    {
	    	ImageView sms5_img = (ImageView)pay_money.findViewById(R.id.img_sms5);
	    	sms5_img.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub							
						startActivitySms(1);					
				}
			});
	    }
	    
	    public void setupSms10()
	    {
	    	ImageView sms10_img = (ImageView)pay_money.findViewById(R.id.img_sms10);
	    	sms10_img.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub							
						startActivitySms(2);					
				}
			});
	    }
	    
	    public void startActivityCard(String sCenter)
	    {
	    	Intent payIntent = new Intent().setClass(this, PayCard.class);
	    	payIntent.putExtra("Network", sCenter);
			startActivity(payIntent);
	    }
	    
	    public void startActivitySms(int nType)
	    {
	    	
	    		Intent payIntent = new Intent().setClass(this, PaySms.class);
	    		SmsItem item = null;
	    		if(nType == 1)
	    			item = application.getSms5();
	    		if(nType == 2)
	    			item = application.getSms10();
	    		if(nType == 3)
	    			item = application.getSms15();
	    	if(item != null)
	    	{    		
	    		payIntent.putExtra("Number",item.sNumber);
	    		
	    		payIntent.putExtra("Content", item.sContent);
	    		startActivity(payIntent);
			}
	    	else
	    	{
	    		//pay money don't successfully
	    	}
	    }
	    
	   /*==================End Payment============================*/
	    
	    
	 /*=================Update version===========================*/
	 
	 
	 Handler handler_update = new Handler() {

         public void handleMessage(Message msg) {
             super.handleMessage(msg);

             switch(msg.what) {

             case 0:
            	 //updateVersionDialog();
                 break;         
             }
         }

     }; 
     
     /*-----------------------------------------------------------*/
	 private  void startCheckVersion()
	 {
		 Intent intent = new Intent(this, GetVersionService.class);
			startService(intent);
			GetVersionThread.setonGetDataCompleteListener(new OnUploadingCompleteListener() {
						@Override
						public void OnGetDataComplete(Context context,String response)
						{
							// TODO Auto-generated method stub
							
							urlPath = response;
							if (!urlPath.equalsIgnoreCase("null") || !urlPath.equalsIgnoreCase(""))
							{
								handler_update.sendEmptyMessage(0);
							}
						}

						@Override
						public void onGetVideoComplete(Context context,
								ArrayList<videoItem> listVideo) {
							// TODO Auto-generated method stub
							
						}
					});
	 }
	 
	 /*------------------------------------------------------------------*/
	 private void updateVersionDialog() {
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setMessage(message);
			alert.setPositiveButton(getString(R.string.text_ok),

			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					dialog.cancel();
					updateNewVersion();
				}
			});
			alert.setNegativeButton(getString(R.string.text_no),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							dialog.cancel();
						}
					});
			alert.show();
		}
	 /*----------------------------------------------------------*/
	 
	 private void updateNewVersion() {
			boolean available = false;
			Intent intent = new Intent(this, DownloadService.class);
			if (Environment.MEDIA_MOUNTED.equals(Environment
					.getExternalStorageState())) {
				path = Environment.getExternalStorageDirectory().getAbsolutePath()
						+ "/ChatVideo/install/" + this.getString(R.string.app_name)
						+ ".apk";
				available = true;
			} else {
				File internalCacheDir = this.getCacheDir();
				// apparently on some configurations this can come back as null
				if (internalCacheDir == null) {
					available = false;
				} else {
					path = internalCacheDir.getAbsolutePath() + "/ChatVideo/install/"
							+ this.getString(R.string.app_name) + ".apk";

					available = true;
				}

			}
			if (available) {
				Bundle sendBundle = new Bundle();
				sendBundle.putString("url", urlPath);
				sendBundle.putString("fileName", this.getString(R.string.app_name)
						+ ".apk");
				sendBundle.putString("name", this.getString(R.string.app_name)
						+ ".apk");
				intent.putExtras(sendBundle);
				ServiceQueueDownloadUtil
						.setOnDownloadStartListener(new OnDownloadStartListener() {
							@Override
							public void onDownloadStart(final IDownloadedItem item) {
								// TODO Auto-generated method stub
								Thread t = new Thread(new Runnable() {
									@Override
									public void run() {
										// TODO Auto-generated method stub
										ServiceQueueDownloadUtil
												.requestDumpGet(urlPath);
									}
								});
								t.start();
							}
						});
				ServiceQueueDownloadUtil
						.setOnDownloadCompleteListener(new OnDownloadCompleteListener() {
							@Override
							public void onDownloadComplete(final Context context,
									final IDownloadedItem item) {
								// TODO Auto-generated method stub
								File apkFile = new File(path);
								Intent i2 = new Intent();
								i2.setAction(android.content.Intent.ACTION_VIEW);
								i2.setDataAndType(Uri.fromFile(apkFile),
										"application/vnd.android.package-archive");
								startActivity(i2);
							}
						});
				startService(intent);
			} else {
				Toast.makeText(getParent(), "Lỗi,vui lòng kiểm tra lại bộ nhớ!", 0)
						.show();
			}

		}
	 /*-----------------------------------------------------------------------------------*/
	 
	 
	 /*=================Update version===========================*/
		
}
